//
//  Friend_groupListVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/9/15.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "Friend_groupListVC.h"
#import "FriendGroupCell.h"
#import "YBApiManager+Friend.h"

@interface Friend_groupListVC ()

@property (nonatomic, strong) Address_groupItem *originGroup;
@property (nonatomic, strong) Address_groupItem *selectedGroup;

@end
@implementation Friend_groupListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.title = @"移动分组";
    for (Address_groupItem *item in kUsermanager.friend_groupArray) {
        if ([item.name isEqualToString:@"黑名单"] == YES) {
            continue;
        }
        [self.dataSource addObject:item];
        if ([item.sort_id isEqualToString:self.friendItem.sort_id] == YES) {
            self.originGroup =
            self.selectedGroup = item;
        }
    }
}
- (void)setupUI {
    [self.tableView customRegisterClassWithName:@"FriendGroupCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FriendGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FriendGroupCell" forIndexPath:indexPath];
    Address_groupItem *item = [self.dataSource objectAtIndex:indexPath.row];
    
    cell.groupNameLabel.text = item.name;
    cell.selectedImgView.hidden = (item != self.selectedGroup);
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    self.originGroup = self.selectedGroup;
    self.selectedGroup = self.dataSource[indexPath.row];
    [self.tableView reloadData];
    @weakify(self);
    [MBProgressHUD showActivityMessageInView:@""];
    [[YBApiManager.shareManager moveFriendToNewGroupWithSortID:self.selectedGroup.sort_id friend_id:self.friendItem.friend_id] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        @strongify(self);
        [kUsermanager updateFriend_groupList];
        if (self.groupChanged) {
            self.groupChanged(self.selectedGroup);
        }
        [self.navigationController popViewControllerAnimated:YES];

    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
        @strongify(self);
        self.selectedGroup = self.originGroup;
        [self.tableView reloadData];
    }];
    
}


@end
